package com.resou.reader.utils;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.resou.reader.ReSouApplication;
import com.resou.reader.view.Loading;
import com.resou.reader.view.NetErrorFragment;

import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

/**
 * Created by ${Garrett} on 2018/10/25.
 * Contact me krouky@outlook.com
 */
public class ErrorUtils {

    /**
     * 取消加载框并提示消息
     *
     * @param msg 失败原因
     */
    public static void showError(String msg) {
        Loading.getInstance().dismiss();
        if (!TextUtils.isEmpty(msg))
            Toast.makeText(ReSouApplication.getRSApplication(), msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 取消加载框并提示消息打印异常栈信息
     *
     * @param throwable 错误
     */
    public static void showError(Throwable throwable) {
        Loading.getInstance().dismiss();
        throwable.printStackTrace();

        if (throwable instanceof UnknownHostException) {
            Toast.makeText(ReSouApplication.getRSApplication(), "请检查是否打开手机网络", Toast.LENGTH_SHORT).show();
        } else if (throwable instanceof TimeoutException) {
            //直接展示加载失败view
            Toast.makeText(ReSouApplication.getRSApplication(), "服务器连接超时", Toast.LENGTH_SHORT).show();
        } else {
            if (!TextUtils.isEmpty(throwable.getMessage()))
                Toast.makeText(ReSouApplication.getRSApplication(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private static NetErrorFragment mNetErrorFragment;

    public static void showErrorFragment(@IdRes int layoutId, FragmentManager fragmentManager, final doNextCallback callback) {
        if (mNetErrorFragment == null) {
            mNetErrorFragment = new NetErrorFragment(new NetErrorFragment.OnClick() {
                @Override
                public void onClick() {
                    callback.retry();
                    mNetErrorFragment.dismiss();
                }
            });
        }
        mNetErrorFragment.show(layoutId, fragmentManager);
    }

    public static void showEmpty(Context context, final ViewGroup rootView, @LayoutRes int resource, final doNextCallback callback) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View emptyView = inflater.inflate(resource, null);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.moveTo();
            }
        });
        rootView.addView(emptyView);
    }

    public abstract static class doNextCallback {
        public void retry() {

        }

        public void moveTo() {

        }
    }
}
